package cn.edu.hzvtc.haowen.controller;

import java.util.Arrays;
import java.util.List;
import javax.servlet.http.HttpServletResponse;

import cn.edu.hzvtc.haowen.common.utils.DateUtils;
import cn.edu.hzvtc.haowen.common.utils.StringUtils;
import cn.edu.hzvtc.haowen.common.utils.ip.IpUtils;
import cn.edu.hzvtc.haowen.common.utils.uuid.IdUtils;
import cn.edu.hzvtc.haowen.domain.WenjuanInfo;
import cn.edu.hzvtc.haowen.dto.WenjuanAnswerWithPwd;
import cn.edu.hzvtc.haowen.service.IWenjuanInfoService;
import net.bytebuddy.implementation.bind.annotation.Default;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import cn.edu.hzvtc.haowen.common.annotation.Log;
import cn.edu.hzvtc.haowen.common.core.controller.BaseController;
import cn.edu.hzvtc.haowen.common.core.domain.AjaxResult;
import cn.edu.hzvtc.haowen.common.enums.BusinessType;
import cn.edu.hzvtc.haowen.domain.WenjuanAnswer;
import cn.edu.hzvtc.haowen.service.IWenjuanAnswerService;
import cn.edu.hzvtc.haowen.common.utils.poi.ExcelUtil;
import cn.edu.hzvtc.haowen.common.core.page.TableDataInfo;

/**
 * 问卷答卷Controller
 * 
 * @author haowen
 * @date 2024-05-15
 */
@RestController
@RequestMapping("/wenjuan/wenjuan_answer")
public class WenjuanAnswerController extends BaseController
{
    @Autowired
    private IWenjuanAnswerService wenjuanAnswerService;
    @Autowired
    private IWenjuanInfoService wenjuanInfoService;

    /**
     * 查询user问卷答卷历史记录
     */
    @PreAuthorize("@ss.hasPermi('mine:wenjuan_mine:list_finished')")
    @GetMapping("/history")
    public TableDataInfo history(WenjuanAnswer wenjuanAnswer)
    {
        wenjuanAnswer.setAnswerBy(getUserId().intValue());
        startPage();
        List<WenjuanAnswer> list = wenjuanAnswerService.selectWenjuanAnswerList(wenjuanAnswer);
        return getDataTable(list);
    }


    /**
     * 查询问卷答卷列表
     */
    @PreAuthorize("@ss.hasPermi('wenjuan:wenjuan_answer:list')")
    @GetMapping("/list")
    public TableDataInfo list(WenjuanAnswer wenjuanAnswer)
    {
        startPage();
        List<WenjuanAnswer> list = wenjuanAnswerService.selectWenjuanAnswerList(wenjuanAnswer);
        return getDataTable(list);
    }

    /**
     * 导出问卷答卷列表
     */
    @PreAuthorize("@ss.hasPermi('wenjuan:wenjuan_answer:export')")
    @Log(title = "问卷答卷", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, WenjuanAnswer wenjuanAnswer)
    {
        List<WenjuanAnswer> list = wenjuanAnswerService.selectWenjuanAnswerList(wenjuanAnswer);
        ExcelUtil<WenjuanAnswer> util = new ExcelUtil<WenjuanAnswer>(WenjuanAnswer.class);
        util.exportExcel(response, list, "问卷答卷数据");
    }

    /**
     * 获取问卷答卷详细信息
     */
    @PreAuthorize("@ss.hasPermi('wenjuan:wenjuan_answer:query')")
    @GetMapping(value = "/{answerId}")
    public AjaxResult getInfo(@PathVariable("answerId") Integer answerId)
    {
        return success(wenjuanAnswerService.selectWenjuanAnswerByAnswerId(answerId));
    }

    /**
     * 新增问卷答卷
     */
    @PreAuthorize("@ss.hasPermi('wenjuan:wenjuan_answer:add')")
    @Log(title = "问卷答卷", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody WenjuanAnswer wenjuanAnswer)
    {
        wenjuanAnswer.setAnswerUuid(IdUtils.simpleUUID());
        // 获取当前用户的id和用户名,因为允许匿名答卷，所以不一定有用户信息
        try{
            if (getUserId() == null || getUserId()==0 ) {
                wenjuanAnswer.setAnswerBy(0);
                wenjuanAnswer.setAnswerUserName("匿名用户");
            }
        }catch (Exception e){
            logger.info("get userinfo error, set answerBy=0, answerUserName=匿名用户");
            wenjuanAnswer.setAnswerBy(0);
            wenjuanAnswer.setAnswerUserName("匿名用户");
        }
        // 获取ip地址
        try{
            wenjuanAnswer.setIpaddr(IpUtils.getIpAddr());
        }catch (Exception e){
            logger.error("get ipaddr error");
            wenjuanAnswer.setIpaddr("0.0.0.0");
        }
        return toAjax(wenjuanAnswerService.insertWenjuanAnswer(wenjuanAnswer));
    }

    /**
     * 修改问卷答卷
     */
    @PreAuthorize("@ss.hasPermi('wenjuan:wenjuan_answer:edit')")
    @Log(title = "问卷答卷", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody WenjuanAnswer wenjuanAnswer)
    {
        // 获取ip地址
        try{
            wenjuanAnswer.setIpaddr(IpUtils.getIpAddr());
        }catch (Exception e){
            logger.error("get ipaddr error");
            wenjuanAnswer.setIpaddr("0.0.0.0");
        }
        return toAjax(wenjuanAnswerService.updateWenjuanAnswer(wenjuanAnswer));
    }

    /**
     * 删除问卷答卷
     */
    @PreAuthorize("@ss.hasPermi('wenjuan:wenjuan_answer:remove')")
    @Log(title = "问卷答卷", businessType = BusinessType.DELETE)
	@DeleteMapping("/{answerIds}")
    public AjaxResult remove(@PathVariable Integer[] answerIds)
    {
        return toAjax(wenjuanAnswerService.deleteWenjuanAnswerByAnswerIds(answerIds));
    }



    /**
     * 新增问卷答卷
     */
    // 不需要写@log，避免不必要的异常或者错误日志
    // 无需权限验证 src/main/java/cn/edu/hzvtc/haowen/framework/config/SecurityConfig.java
    @PostMapping("/u/{uuid}")
    public AjaxResult addWenjuanAnswer(@RequestBody WenjuanAnswerWithPwd wenjuanAnswerWithPwd , @PathVariable String uuid)
    {

        logger.debug("============== user adddWenjuanAnswer ================");

        WenjuanInfo wenjuanInfo = wenjuanInfoService.selectWenjuanInfoByWenjuanUuid(wenjuanAnswerWithPwd.getAnswerWenjuanUuid());

        if (wenjuanInfo == null) {
            logger.info("The wenjuan is not exist: "+wenjuanAnswerWithPwd.getAnswerWenjuanUuid());
            return warn("问卷不存在");
        }

        if (checkWenjuanAnswerUser(wenjuanAnswerWithPwd, wenjuanInfo) == false) {
            logger.info("The wenjuan is private or dept, the user no permission to answer it.");
            return warn("无权限");
        }

        WenjuanAnswer wenjuanAnswer = new WenjuanAnswer();

        wenjuanAnswer.setAnswerUuid(IdUtils.simpleUUID());
        wenjuanAnswer.setAnswerWenjuanId(wenjuanInfo.getWenjuanId());
        wenjuanAnswer.setAnswerWenjuanUuid(wenjuanAnswerWithPwd.getAnswerWenjuanUuid());
        wenjuanAnswer.setAnswerWenjuanTitle(wenjuanInfo.getWenjuanTitle());
        wenjuanAnswer.setAnswerContent(wenjuanAnswerWithPwd.getAnswerContent());
        wenjuanAnswer.setCreateTime(DateUtils.getNowDate());



        // 获取ip地址
        wenjuanAnswer.setIpaddr(IpUtils.getIpAddr());

        // 获取当前用户的id和用户名,因为允许匿名答卷，所以不一定有用户信息
        if(!checkLoginUser()){
            logger.info("get userinfo error, maybe the user is Anonymous, set answerBy=0, answerUserName=匿名用户");
            wenjuanAnswer.setAnswerBy(0);
            wenjuanAnswer.setAnswerUserName("匿名用户");
            return toAjax(wenjuanAnswerService.insertWenjuanAnswer(wenjuanAnswer));
        }


        if(checkLoginUser()) {
            wenjuanAnswer.setAnswerBy(getUserId().intValue());
            wenjuanAnswer.setAnswerUserName(getUsername());
        }else {
            logger.info("get userinfo error, maybe the user is Anonymous, set answerBy=0, answerUserName=匿名用户");
            wenjuanAnswer.setAnswerBy(0);
            wenjuanAnswer.setAnswerUserName("匿名用户");
        }


        return toAjax(wenjuanAnswerService.insertWenjuanAnswer(wenjuanAnswer));
    }


    /**
     * 判断用户是否有权限提交答卷
     *
     */
    public Boolean checkWenjuanAnswerUser(WenjuanAnswerWithPwd wenjuanAnswerWithPwd,WenjuanInfo wenjuanInfo) {
        // 1 公开的问卷
        if (
                WenjuanTypeToUser.PUBLIC.getType().equals(
                    wenjuanInfo.getWenjuanType()
                )
        ) {
            return true;
        }
        // 2 私密的问卷
        else if(
                WenjuanTypeToUser.PRIVATE.getType().equals(
                    wenjuanInfo.getWenjuanType()
                )
        ) {
            // 判断是否有密码
            if (StringUtils.isEmpty(wenjuanInfo.getWenjuanPassword())) {
                return true;
            } else {
                // 判断密码是否正确
                if (wenjuanInfo.getWenjuanPassword().equals(wenjuanAnswerWithPwd.getPassword())) {
                    return true;
                } else {
                    return false;
                }
            }
        }
        // 3 内部问卷
        else if(
                WenjuanTypeToUser.DEPARTMENT.getType().equals(
                    wenjuanInfo.getWenjuanType()
                )
        ) {

            try {
                getLoginUser();
            }catch (Exception e){
                logger.error("get userinfo error");
                return false;
            }

            // 判断用户部门和问卷部门是否一致
            try {
                if ((getDeptId() + "").equals(wenjuanInfo.getCreateFor())) {
                    return true;
                }

                // 如果问卷的部门是上级或祖籍部门，也可以查看
                else if (
                        Arrays.stream(getLoginUser().getUser().getDept().getAncestors().split(",")).anyMatch(s->s.equals(wenjuanInfo.getCreateFor()))
//                        getLoginUser().getUser().getDept().getAncestors().contains(wenjuanInfo.getCreateFor())
                ){
                    logger.info("the user dept:"+getDeptId()+" is under wenjuan dept:"+wenjuanInfo.getCreateFor()+" , send wenjuan to user.");
                    return true;
                }

                else {
                    return false;
                }
            }catch (Exception e){
                logger.error("get deptid error");
                return false;
            }

        }
        return false;
    }

    /** 判断是否有登录用户 */
    public Boolean checkLoginUser() {
        try {
            getLoginUser();
        }catch (Exception e){
            logger.error("get userinfo error");
            return false;
        }

        try{
            if (getUserId() == null || getUserId()==0 ) {
                return false;
            }else {
                return true;
            }
        }catch (Exception e){
            logger.error("get userinfo error");
            return false;
        }

    }

}
